package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yuanda.erp9.syn.entity.*;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.poi.AipcoCsvData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.pojo.CmsPricesPojo;
import com.yuanda.erp9.syn.service.erp9.AipcoDataImportService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @desc   Aipco数据导入的实现类
 * @author linuo
 * @time   2022年11月28日11:00:12
 */
@Service
@Slf4j
public class AipcoDataImportServiceImpl extends CsvSaveImpl implements AipcoDataImportService {
    /** 供应商名称 */
    private static final String SUPPLIER = "Aipco";

    /** 供应商id */
    private static final String SUPPLIER_ID = "US000000073";

    /**
     * 数据插入
     * @param topicUpdateLogId 系统主体更新日志记录表id
     * @param filePath 文件路径
     */
    @Override
    public String importCmsGoodsPojo(Long topicUpdateLogId, String filePath) {
        Integer supplierId = suppliersCache.get(SUPPLIER);
        if(supplierId == null){
            // 插入供应商数据
            CmsSuppliersTempEntity cmsSuppliersTempEntity = new CmsSuppliersTempEntity();
            cmsSuppliersTempEntity.setSupplierUs(SUPPLIER_ID);
            cmsSuppliersTempEntity.setName(SUPPLIER);
            cmsSuppliersTempEntity.setTag(0);
            int insert = cmsSuppliersTempMapper.insert(cmsSuppliersTempEntity);
            if(insert > 0){
                supplierId = cmsSuppliersTempEntity.getSupplierid();
            }
        }

        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());

        try {
            // 读取csv数据
            List<String[]> strings = CsvReadUtils.parseCSV(filePath);
            if(strings != null && strings.size() > 0){
                if(topicUpdateLogId != null){
                    // 插入系统主体更新数量日志记录表数据
                    Integer integer = cmsTopicUpdateSumLogService.insertBySum((long) strings.size(), topicUpdateLogId);
                    if(integer > 0){
                        log.info("插入系统主体更新数量日志记录表数据成功");
                    }
                }

                log.info("创建Aipco数据导入任务开始");
                AtomicInteger row = new AtomicInteger();
                for (int i = 0; i < strings.size(); i++) {
                    String[] string = strings.get(i);
                    row.getAndIncrement();
                    if (string.length == 23) {
                        AipcoCsvData aipcoCsvData = AipcoCsvData.toAipcoCsvDataFormat(string, i);

                        // 过滤掉库存、品牌为null或库存为0的数据
                        if(aipcoCsvData.getInventory() == null || aipcoCsvData.getInventory() == 0 || Strings.isNullOrEmpty(aipcoCsvData.getManufacturer()) || aipcoCsvData.getManufacturer().contains("?")){
                            continue;
                        }

                        CmsGoodsPojo cmsGoodsPojo = packageCmsGoodsPojo(aipcoCsvData, supplierId);
                        objectMaster.add(cmsGoodsPojo);
                    }
                }
            }
        }finally {
            objectMaster.isBegin = false;
        }

        log.info("创建Aipco数据导入任务结束");
        return "ok";
    }

    /**
     * Aipco数据组装
     * @param aipcoCsvData Aipco数据解析
     */
    private CmsGoodsPojo packageCmsGoodsPojo(AipcoCsvData aipcoCsvData, Integer supplierId) {
        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();

        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();

        cmsGoodsEntity.setAdminid(0);
        cmsGoodsEntity.setTenantsid(0);
        cmsGoodsEntity.setSupplier(supplierId);

        String partNumber = aipcoCsvData.getMpn();
        partNumber = partNumber.replaceAll("\\+", "_");
        partNumber = partNumber.replaceAll(" ", "_");
        partNumber = partNumber.replaceAll("/", "_");
        partNumber = partNumber.replaceAll("\\?", "_");
        partNumber = partNumber.replaceAll("%", "_");
        partNumber = partNumber.replaceAll("#", "_");
        partNumber = partNumber.replaceAll("&", "_");
        partNumber = partNumber.replaceAll("=", "_");

        // 产品唯一标识
        //String sign = "_"+ partNumber + "_" + "1" + "73";

        String sign = SUPPLIER + "_" + aipcoCsvData.getManufacturer() + "_" + partNumber + "_" + aipcoCsvData.getRow();
        sign = sign.replaceAll(" ", "");

        String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, "", "", "", "", "", cmsGoodsEntity.getSupplier());

        //log.info("incodes= " + incodes + " ,row= " + aipcoCsvData.getRow());

        cmsGoodsEntity.setIncodes(incodes);
        cmsGoodsEntity.setGoodid(incodes);

        cmsGoodsEntity.setClassifyid(0);
        cmsGoodsEntity.setImg("");
        cmsGoodsEntity.setType(0);
        cmsGoodsEntity.setStatus(1);
        cmsGoodsEntity.setStatusMsg(null);
        cmsGoodsEntity.setDataType(1);

        // 名称
        String mpn = aipcoCsvData.getMpn();
        cmsGoodsEntity.setModel(mpn);

        // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
        String manufacturer = aipcoCsvData.getManufacturer();
        Integer i = brandCache.get(manufacturer);
        if (i == null) {
            // 插入品牌数据
            Integer brandId = insertBrand(manufacturer);
            cmsGoodsEntity.setBrand(brandId);
        }else{
            cmsGoodsEntity.setBrand(i);
        }

        cmsGoodsEntity.setIsSampleApply(0);
        cmsGoodsEntity.setBatch("");
        cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);
        cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);

        // 库存
        Integer inventory = aipcoCsvData.getInventory();
        cmsGoodsEntity.setRepertory(inventory);

        // 库存所在地
        cmsGoodsEntity.setRepertoryArea("加拿大");

        // 国内交货日期
        cmsGoodsEntity.setDomesticDate("7-10个工作日");

        // 交货时间
        cmsGoodsEntity.setHongkongDate("5-8个工作日");

        cmsGoodsEntity.setPublish(1);

        // 购买类型0单个买1整包买
        cmsGoodsEntity.setPayType(0);

        // 最小起订
        cmsGoodsEntity.setMinimumOrder(aipcoCsvData.getMoq());

        // 增量
        if(null != aipcoCsvData.getMoq()){
            cmsGoodsEntity.setIncremental(aipcoCsvData.getMoq());
        }else{
            cmsGoodsEntity.setIncremental(1L);
        }

        // mpq
        cmsGoodsEntity.setMpq(StringUtils.isEmpty(aipcoCsvData.getMoq()) ? 1 : aipcoCsvData.getMoq());

        // 交货地区
        cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());

        cmsGoodsEntity.setSales(0);
        cmsGoodsEntity.setClick(0);
        cmsGoodsEntity.setVisitor(0);

        String rohs = aipcoCsvData.getRohs();
        if(!Strings.isNullOrEmpty(rohs)){
            JSONObject json = new JSONObject();
            json.put("ROHS", rohs);
            cmsGoodsEntity.setParams(json.toJSONString());
        }

        cmsGoodsEntity.setCreatedAt(DateUtils.now());
        cmsGoodsEntity.setUpdatedAt(DateUtils.now());

        cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
        cmsGoodsEntity.setSplName(SUPPLIER);
        cmsGoodsEntity.setBrandName(manufacturer);

        if(null == cmsGoodsEntity.getMinimumOrder() || cmsGoodsEntity.getMinimumOrder() == 0){
            cmsGoodsEntity.setMinimumOrder(1L);
        }

        // 组装阶梯价格信息
        List<CmsPricesEntity> list = createCmsPrices(aipcoCsvData, cmsGoodsEntity.getGoodid());
        cmsGoodsPojo.setCmsPricesEntityList(list);

        // 根据起订金额和阶梯配置计算最小起订量
        Long calculateMoq = MoqUtil.getMoq(cmsGoodsEntity.getMinimumOrder(), cmsGoodsEntity.getIncremental(), BigDecimal.valueOf(30), list);
        if(calculateMoq != null && calculateMoq > cmsGoodsEntity.getMinimumOrder()){
            cmsGoodsEntity.setMinimumOrder(calculateMoq);
        }

        // 最小起订
        cmsGoodsEntity.setMinimumOrder(getMoqByLadderPriceList(cmsGoodsEntity.getMinimumOrder(), list));

        // 计算单价
        //cmsGoodsEntity.setUnitPrice(calculateUnitPrice(list));

        List<CmsPricesPojo> prices = new ArrayList<>();
        for(CmsPricesEntity cmsPricesEntity : list){
            CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
            BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
            prices.add(cmsPricesPojo);
        }

        // 更新阶梯价格配置到商品表
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
        if(!jsonArray.isEmpty()){
            cmsGoodsEntity.setPrices(jsonArray.toString());
        }

        // 费率
        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

        // 从费率的json中获取信息补充到商品表实体中
        cmsGoodsEntity = addRateInfo(cmsGoodsEntity, data);

        // 封装
        cmsGoodsEntity.setPackage_("");

        // 包装
        cmsGoodsEntity.setPacking("0");

        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

        // 组装商品表-副表信息
        cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(cmsGoodsEntity.getGoodid(), cmsGoodsEntity.getInspectionChargesFee()));

        return cmsGoodsPojo;
    }

    /**
     * 组装阶梯价格信息
     * @param aipcoCsvData Aipco数据解析
     * @param goodId 商品id
     */
    private List<CmsPricesEntity> createCmsPrices(AipcoCsvData aipcoCsvData, String goodId) {
        List<CmsPricesEntity> result = new ArrayList<>();

        Long qtyBreak1 = aipcoCsvData.getQtyBreak1();
        String priceBreak1 = aipcoCsvData.getPriceBreak1();
        Long qtyBreak2 = aipcoCsvData.getQtyBreak2();

        int position = 0;
        Long max;
        // 一级阶梯价格
        if(qtyBreak1 != null && !Strings.isEmpty(priceBreak1)){

            if(null != qtyBreak2){
                max = qtyBreak2 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, qtyBreak1, max, priceBreak1, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 二级阶梯价格
        String priceBreak2 = aipcoCsvData.getPriceBreak2();
        Long qtyBreak3 = aipcoCsvData.getQtyBreak3();
        if(qtyBreak2 != null && !Strings.isEmpty(priceBreak2)){

            if(null != qtyBreak3){
                max = qtyBreak3 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, qtyBreak2, max, priceBreak2, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 三级阶梯价格
        String priceBreak3 = aipcoCsvData.getPriceBreak3();
        Long qtyBreak4 = aipcoCsvData.getQtyBreak4();
        if(qtyBreak3 != null && !Strings.isEmpty(priceBreak3)){

            if(null != qtyBreak4){
                max = qtyBreak4 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, qtyBreak3, max, priceBreak3, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 四级阶梯价格
        String priceBreak4 = aipcoCsvData.getPriceBreak4();
        Long qtyBreak5 = aipcoCsvData.getQtyBreak5();
        if(qtyBreak4 != null && !Strings.isEmpty(priceBreak4)){

            if(null != qtyBreak5){
                max = qtyBreak5 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, qtyBreak4, max, priceBreak4, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 五级阶梯价格
        String priceBreak5 = aipcoCsvData.getPriceBreak5();
        Long qtyBreak6 = aipcoCsvData.getQtyBreak6();
        if(qtyBreak5 != null && !Strings.isEmpty(priceBreak5)){

            if(null != qtyBreak6){
                max = qtyBreak6 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, qtyBreak5, max, priceBreak5, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 六级阶梯价格
        String priceBreak6 = aipcoCsvData.getPriceBreak6();
        if(qtyBreak6 != null && !Strings.isEmpty(priceBreak6)){
            result.add(createCmsPriceData(goodId, qtyBreak6, 0L, priceBreak6, CurrencyEnum.DOLLAR.getCode(), position));
        }

        return result;
    }
}